﻿using UnityEngine;
using System;
using System.Collections;
using XLua;
using Baiyy.Controllers;

[System.Serializable]
public class LuaInjection {
	public string name;
	public GameObject value;
}

[LuaCallCSharp]
public class LuaController : BaseController {

	#region vars
	public TextAsset luaScript;
	public LuaInjection[] luaInjections;

	internal static LuaEnv sLuaEnv = new LuaEnv();
	internal static float sLuaGCTime = 0.0f;
	internal const float LUA_GC_INTERVAL = 1.0f;

	private Action luaInitData, luaInitState, luaInitView;
	private Action luaUpdateData, luaUpdateState, luaUpdateView;
	private Action luaDestroyData, luaDestroyState, luaDestroyView;

	private LuaTable scriptEnv;
	#endregion

	#region methods
	public static void DoString(string chunk, string chunkName = "chunk", LuaTable env = null) {
		Baiyy.Console.Debug (chunk);
		sLuaEnv.DoString (chunk, chunkName, env);
	}
	#endregion

	#region overrides
	protected override void InitData () {
		scriptEnv = sLuaEnv.NewTable ();

		LuaTable meta = sLuaEnv.NewTable ();
		meta.Set ("__index", sLuaEnv.Global);
		scriptEnv.SetMetaTable (meta);
		meta.Dispose ();

		scriptEnv.Set ("self", this);
		foreach (LuaInjection luaInjection in luaInjections) {
			scriptEnv.Set (luaInjection.name, luaInjection.value);
		}

		if (luaScript != null) {
			sLuaEnv.DoString (luaScript.text, "LuaController", scriptEnv);
		}

		scriptEnv.Get ("initData", out luaInitData);
		scriptEnv.Get ("initState", out luaInitState);
		scriptEnv.Get ("initView", out luaInitView);
		scriptEnv.Get ("updateData", out luaUpdateData);
		scriptEnv.Get ("updateState", out luaUpdateState);
		scriptEnv.Get ("updateView", out luaUpdateView);
		scriptEnv.Get ("destroyData", out luaDestroyData);
		scriptEnv.Get ("destroyState", out luaDestroyState);
		scriptEnv.Get ("destroyView", out luaDestroyView);

		if (luaInitData != null) {
			luaInitData ();
		}
	}

	protected override void InitState() {
		if (luaInitState != null) {
			luaInitState ();
		}
	}

	protected override void InitView() {
		if (luaInitView != null) {
			luaInitView ();
		}
	}

	protected override void UpdateData() {
		if (luaUpdateData != null) {
			luaUpdateData ();
		}
	}

	protected override void UpdateState() {
		if (luaUpdateState != null) {
			luaUpdateState ();
		}
	}

	protected override void UpdateView() {
		if (luaUpdateView != null) {
			luaUpdateView ();
		}
	}

	protected override void DestroyData() {
		if (luaDestroyData != null) {
			luaDestroyData ();
		}
	}

	protected override void DestroyState() {
		if (luaDestroyState != null) {
			luaDestroyState ();
		}
	}

	protected override void DestroyView() {
		if (luaDestroyView != null) {
			luaDestroyView ();
		}
	}


	#endregion
}
